package com.zhongjian.technologycal.mall.activity.main.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.activity.main.activity.CourseDetailsActivity;
import com.zhongjian.technologycal.mall.activity.main.activity.CourseDetailsNoPayActivity;
import com.zhongjian.technologycal.mall.activity.main.activity.PaymentActivity;
import com.zhongjian.technologycal.mall.activity.personal.SettingsActivity;
import com.zhongjian.technologycal.mall.adapter.HotRecommendAdapter;
import com.zhongjian.technologycal.mall.base.BaseUserFragment;
import com.zhongjian.technologycal.mall.bean.CourseListBean;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.ToastUitl;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/12/11.
 */

public class HotRecommendFragment extends BaseUserFragment {
    public static final String CATEGORY_NAME = "com.nanchen.aiyagirl.module.category.CategoryFragment.CATEGORY_NAME";
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.tabs_refresh_layout)
    RefreshLayout tabs_refresh_layout;
    private HotRecommendAdapter hotRecommendAdapter;
    private List<CourseListBean> listItems;
    private int page = 0;
    private int pageNum = 10;
    private String tabsId;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    hotRecommendAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };


    @Override
    protected void init() {
        tabsId = getArguments().getString("tabsId");
        initRequestMembersArea(Integer.valueOf(tabsId));
        listItems = new ArrayList<>();
        hotRecommendAdapter = new HotRecommendAdapter(listItems);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(hotRecommendAdapter);
        hotRecommendAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
//        hotRecommendAdapter.isFirstOnly(false);
        recyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                //事件处理
                Intent intent = new Intent();
                if(listItems.get(position).isCanApply() == true){
                    intent.setClass(getActivity(),CourseDetailsActivity.class);
                    intent.putExtra("courseId",listItems.get(position).getId());
                    startActivity(intent);
                }else if(listItems.get(position).isCanApply() == false){
                    intent.setClass(getActivity(),CourseDetailsNoPayActivity.class);
                    intent.putExtra("courseId",listItems.get(position).getId());
                    startActivity(intent);
                }

            }
        });

        tabs_refresh_layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                page = 0;
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initRequestMembersArea(Integer.valueOf(tabsId));
                        refreshlayout.finishRefresh();
                        refreshlayout.setLoadmoreFinished(false);
                    }
                }, 1000);
            }
        });
        tabs_refresh_layout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(final RefreshLayout refreshlayout) {
                page ++ ;
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initRequestMembersArea(Integer.valueOf(tabsId));
                        refreshlayout.finishLoadmore();
                    }
                }, 1000);
            }
        });


    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_hot_recommend;
    }

    public static Fragment getInstance(Bundle bundle) {
        HotRecommendFragment categoryFragment = new HotRecommendFragment();
        categoryFragment.setArguments(bundle);
        return categoryFragment;
    }

    private void initRequestMembersArea(int typeId) {
        if (!NetWorkUtils.isNetConnected(getActivity())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getActivity())
                .getUrlRequestCommercialcollegeCoursesbytype(typeId, page, pageNum,
                        new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                            }

                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                try {
                                    JSONObject jsonObject = new JSONObject(responseBody.string());
                                    JSONArray jsonRecommend = jsonObject.optJSONArray("data");
                                    Gson gson = new Gson();
                                    List<CourseListBean> forList = new ArrayList<>();
                                    for (int i = 0; i < jsonRecommend.length(); i++) {
                                        CourseListBean courseListBean = gson.fromJson(jsonRecommend.optString(i).toString(),
                                                CourseListBean.class);
                                        forList.add(courseListBean);

                                    }
                                    setData(forList);

                                } catch (Exception e) {
                                    e.printStackTrace();

                                }

                            }
                        });

    }

    private void setData(List<CourseListBean> foreshowList) {
        if (page == 0) {
            listItems.clear();
        }
        for (CourseListBean vo : foreshowList) {
            listItems.add(vo);
        }
        handler.sendEmptyMessage(0);

    }
}
